package com.glory.hikvisionmobile.activity;

import android.os.Bundle;
import android.view.View;
import android.widget.CheckBox;
import android.widget.FrameLayout;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;

import androidx.core.widget.NestedScrollView;
import androidx.recyclerview.widget.DefaultItemAnimator;
import androidx.recyclerview.widget.DividerItemDecoration;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;

import com.chad.library.adapter.base.BaseQuickAdapter;
import com.glory.hikvisionmobile.R;
import com.glory.hikvisionmobile.adapter.EqpCheckListAdapter;
import com.glory.hikvisionmobile.base.BaseActivity;
import com.glory.hikvisionmobile.bean.EqpManger.EqpCheckListBean;
import com.glory.hikvisionmobile.bean.from.CheckPlanBean;
import com.glory.hikvisionmobile.bean.from.LocationBean;
import com.glory.hikvisionmobile.bean.from.LocationListBean;
import com.glory.hikvisionmobile.bean.net.BaseResponseBean;
import com.glory.hikvisionmobile.utils.NetUtils;
import com.google.gson.JsonObject;
import com.google.gson.reflect.TypeToken;
import com.lzy.okgo.model.Response;
import com.pda.platform.ui.ui_pdaplatform.callback.FreeUI_DialogEntityCallBack;
import com.pda.platform.ui.ui_pdaplatform.datepicker.CustomDatePicker;
import com.pda.platform.ui.ui_pdaplatform.dialog.FreeUI_GeneralPop;
import com.pda.platform.ui.ui_pdaplatform.entity.FreeUI_AddViewEntity;
import com.pda.platform.ui.ui_pdaplatform.utils_public.FreeApi_DateUtils;
import com.pda.platform.ui.ui_pdaplatform.utils_public.FreeApi_DialogUtils;
import com.pda.platform.ui.ui_pdaplatform.utils_public.FreeApi_PopUtils;
import com.pda.platform.ui.ui_pdaplatform.utils_public.FreeApi_StringUtils;
import com.pda.platform.ui.ui_pdaplatform.utils_public.FreeApi_Utils;

import java.text.ParseException;
import java.util.ArrayList;
import java.util.List;

import butterknife.BindView;
import butterknife.OnClick;

/**
 * FileName: From_CheckPlanFromActivity
 * Author: XJH
 * Date: 2020/2/13 09:36
 * Description: 生产点检计划
 * History:
 */
public class From_CheckPlanFromActivity extends BaseActivity implements BaseQuickAdapter.OnItemClickListener {


    @BindView(R.id.tvClass)
    TextView tvClass;
    @BindView(R.id.ivClassArrow)
    ImageView ivClassArrow;
    @BindView(R.id.flClassList)
    FrameLayout flClassList;
    @BindView(R.id.tvRegion)
    TextView tvRegion;
    @BindView(R.id.ivRegionListArrow)
    ImageView ivRegionListArrow;
    @BindView(R.id.flRegionList)
    FrameLayout flRegionList;
    @BindView(R.id.tvFromType)
    TextView tvFromType;
    @BindView(R.id.ivFromTypeListArrow)
    ImageView ivFromTypeListArrow;
    @BindView(R.id.flFromTypeList)
    FrameLayout flFromTypeList;
    @BindView(R.id.tvBeginTime)
    TextView tvBeginTime;
    @BindView(R.id.ivBeginTimeArrow)
    ImageView ivBeginTimeArrow;
    @BindView(R.id.flBeginTimeList)
    FrameLayout flBeginTimeList;
    @BindView(R.id.tvEndTime)
    TextView tvEndTime;
    @BindView(R.id.ivEndTimeArrow)
    ImageView ivEndTimeArrow;
    @BindView(R.id.flCanTimeList)
    FrameLayout flCanTimeList;
    @BindView(R.id.tvCanTime)
    TextView tvCanTime;
    @BindView(R.id.ivCanTimeArrow)
    ImageView ivCanTimeArrow;
    @BindView(R.id.flEndTimeList)
    FrameLayout flEndTimeList;
    @BindView(R.id.tvSearch)
    TextView tvSearch;
    @BindView(R.id.rvCheckPlanList)
    RecyclerView rvCheckPlanList;
    @BindView(R.id.llMain)
    LinearLayout llMain;
    @BindView(R.id.list_tv1)
    TextView listTv1;
    @BindView(R.id.list_tv2)
    TextView listTv2;
    @BindView(R.id.list_tv3)
    TextView listTv3;
    @BindView(R.id.list_tv4)
    TextView listTv4;
    @BindView(R.id.list_tv5)
    TextView listTv5;
    @BindView(R.id.cbCreate)
    CheckBox cbCreate;
    @BindView(R.id.cbComplete)
    CheckBox cbComplete;
    @BindView(R.id.cbSave)
    CheckBox cbSave;
    private List<String> locationList = new ArrayList();
    private List<String> classList = new ArrayList();
    private List<String> fromTypeList = new ArrayList();
    private FreeUI_GeneralPop locationPop;
    private FreeUI_GeneralPop fromTypePop;
    private FreeUI_GeneralPop ClassPop;
    private String location;
    private EqpCheckListAdapter eqpCheckListAdapter;
    private CustomDatePicker mDatePicker;
    private String beginDate;
    private String endDate;
    private String canDate;
    String isBegin;
    private String fromType;
    private String classes;
    @BindView(R.id.nsScroll)
    NestedScrollView nsScroll;
    @Override
    protected int getLayoutResId() {
        return R.layout.activity_spot_check;
    }

    @Override
    protected void initView() {
        initListView();
        initDatePicker();
        try {
            canDate = FreeApi_DateUtils.longToString(System.currentTimeMillis(), "yyyy-MM-dd HH:mm");
        } catch (ParseException e) {
            e.printStackTrace();
        }
        tvCanTime.setText(canDate);
        rvCheckPlanList.setLayoutManager(new LinearLayoutManager(From_CheckPlanFromActivity.this));
        rvCheckPlanList.setItemAnimator(new DefaultItemAnimator());
        rvCheckPlanList.addItemDecoration(new DividerItemDecoration(From_CheckPlanFromActivity.this, 1));
        eqpCheckListAdapter = new EqpCheckListAdapter(null,false);
        eqpCheckListAdapter.openLoadAnimation(BaseQuickAdapter.ALPHAIN);
        eqpCheckListAdapter.isFirstOnly(true);
        rvCheckPlanList.setAdapter(eqpCheckListAdapter);

        eqpCheckListAdapter.setOnItemClickListener(this);
    }

    private void initDatePicker() {
        long beginTimestamp = FreeApi_DateUtils.str2Long("1992-03-20", false);
        long endTimestamp = FreeApi_DateUtils.str2Long("2222-02-22", false);

        // 通过时间戳初始化日期，毫秒级别
        mDatePicker = new CustomDatePicker(this, timestamp -> {
            switch (isBegin) {
                case "Start" :
                    beginDate = FreeApi_DateUtils.long2Str(timestamp, true);
                    tvBeginTime.setText(beginDate);
                    tvCanTime.setText("");
                    canDate = "";
                    break;
                case "End":
                    endDate = FreeApi_DateUtils.long2Str(timestamp, true);
                    tvEndTime.setText(endDate);
                    tvCanTime.setText("");
                    canDate = "";
                    break;
                case "Can":
                    canDate = FreeApi_DateUtils.long2Str(timestamp, true);
                    tvCanTime.setText(canDate);
                    tvBeginTime.setText("");
                    tvEndTime.setText("");
                    beginDate = "";
                    endDate = "";
                    break;
            }

        }, beginTimestamp, endTimestamp);
        // 不允许点击屏幕或物理返回键关闭
        mDatePicker.setCancelable(true);
        // 不显示时和分
        mDatePicker.setCanShowPreciseTime(true);
        // 不允许循环滚动
        mDatePicker.setScrollLoop(false);
        // 不允许滚动动画
        mDatePicker.setCanShowAnim(false);
    }

    private void initListView() {
        listTv1.setVisibility(View.VISIBLE);
        listTv2.setVisibility(View.VISIBLE);
        listTv3.setVisibility(View.VISIBLE);
        listTv4.setVisibility(View.VISIBLE);
        listTv5.setVisibility(View.VISIBLE);
        listTv1.setText("序号");
        listTv2.setText("点检内容");
        listTv3.setText("描述");
        listTv4.setText("点检时间");
        listTv5.setText("状态");
    }

    @Override
    protected void initData() {
        NetUtils.requestDara("HIK.PdaBaseLocation", this, null, new FreeUI_DialogEntityCallBack<BaseResponseBean<LocationListBean>>
                (new TypeToken<BaseResponseBean<LocationListBean>>() {
                }.getType(), getSupportFragmentManager(), this) {

            @Override
            public void onSuccess(Response<BaseResponseBean<LocationListBean>> response) {
                super.onSuccess(response);
                if (response.body().isSuccess(getApplicationContext(), true, getSupportFragmentManager())) {
                    locationList.clear();
                    List<LocationBean> locationBeans = response.body().getBody().getxPdaLocations();
                    for (LocationBean bean : locationBeans) {
                        locationList.add(bean.getName() + "/" + bean.getDescription());
                    }
                }
            }

            @Override
            public void onError(Response<BaseResponseBean<LocationListBean>> response) {
                super.onError(response);
                loadError(response.getException(), "HIK.PdaBaseLocation");
            }
        });

        NetUtils.getLotTypeList("SpotCheckDepartment", "USER", this, getSupportFragmentManager(), new NetUtils.SelectorCallback() {
            @Override
            public void onSuccess(List<String> list) {
               classList.clear();
               classList.add(0,"");
               classList.addAll(list);
            }

            @Override
            public void onFail(Throwable e, String messageName) {
                loadError(e, messageName);
            }
        });

        NetUtils.getLotTypeList("FormType", "USER", this, getSupportFragmentManager(), new NetUtils.SelectorCallback() {
            @Override
            public void onSuccess(List<String> list) {
                fromTypeList.clear();
                fromTypeList.add(0,"");
                fromTypeList.addAll(list);
            }

            @Override
            public void onFail(Throwable e, String messageName) {
                loadError(e,messageName);
            }
        });

    }

    @Override
    protected FreeUI_AddViewEntity getBaseEntity() {
        freeUI_titleView.setTitle("生产点检计划");
        freeUI_titleView.setRightListener("隐藏", v -> {
            initPermission("Refresh", this, new ActionControlListener() {
                @Override
                public void onControlChangeListener() {
                    nsScroll.setVisibility(nsScroll.getVisibility() == View.VISIBLE ? View.GONE : View.VISIBLE);
                }
            });

        });
        return new FreeUI_AddViewEntity("header", llMain);
    }

    @OnClick({R.id.flClassList, R.id.flRegionList, R.id.flFromTypeList, R.id.flBeginTimeList, R.id.flEndTimeList,R.id.tvSearch,R.id.flCanTimeList})
    public void onViewClicked(View view) {
        switch (view.getId()) {
            case R.id.flRegionList:
                if (locationList.size() <= 0) {
                    showToast("未获取到区域列表", false);
                    return;
                }

                if (locationPop != null) {
                    if (locationPop.isShowing()) {
                        locationPop.dismiss();
                    }
                } else {
                    locationPop = FreeApi_PopUtils.getNormalPop(getApplicationContext(), flRegionList.getWidth(), locationList, ivRegionListArrow, (code, i) -> {
                        tvRegion.setText(code);
                        location = code.split("/")[0];
                    });
                }
                FreeApi_PopUtils.setArrowShow(ivRegionListArrow);
                locationPop.showAsDropDown(flRegionList, 0, 0);
                break;
            case R.id.flClassList:
                if (classList.size() <= 0){
                    showToast("未请求到部门列表",false);
                    return;
                }

                if (ClassPop != null) {
                    if (ClassPop.isShowing()) {
                        ClassPop.dismiss();
                    }
                } else {
                    ClassPop = FreeApi_PopUtils.getNormalPop(getApplicationContext(), flClassList.getWidth(), classList, ivClassArrow, (codeS, i) -> {
                        tvClass.setText(codeS);
                        String[] split = codeS.split("/");
                        classes = split[split.length - 1];
                    });
                }
                FreeApi_PopUtils.setArrowShow(ivClassArrow);
                ClassPop.showAsDropDown(flClassList, 0, 0);
                break;
            case R.id.flFromTypeList:
                if (fromTypeList.size() <= 0){
                    showToast("未请求到表单类型列表",false);
                    return;
                }

                if (fromTypePop != null) {
                    if (fromTypePop.isShowing()) {
                        fromTypePop.dismiss();
                    }
                } else {
                    fromTypePop = FreeApi_PopUtils.getNormalPop(getApplicationContext(), flFromTypeList.getWidth(), fromTypeList, ivFromTypeListArrow, (codeS, i) -> {
                        tvFromType.setText(codeS);
                        String[] split = codeS.split("/");
                        fromType = split[split.length - 1];
                    });


                }
                FreeApi_PopUtils.setArrowShow(ivFromTypeListArrow);
                fromTypePop.showAsDropDown(flFromTypeList, 0, 0);

                break;
            case R.id.flBeginTimeList:
                isBegin = "Start";
                mDatePicker.show(System.currentTimeMillis());
                break;
            case R.id.flEndTimeList:
                isBegin = "End";
                mDatePicker.show(System.currentTimeMillis());
                break;
            case R.id.flCanTimeList:
                isBegin = "Can";
                mDatePicker.show(System.currentTimeMillis());
                break;
            case R.id.tvSearch:

                initPermission("Search", this, new ActionControlListener() {
                    @Override
                    public void onControlChangeListener() {
                        if (FreeApi_StringUtils.isEmpty(location)){
                            showToast("请选择区域",false);
                            return;
                        }

                        if ((!FreeApi_StringUtils.isEmpty(beginDate) && !FreeApi_StringUtils.isEmpty(endDate)) | !FreeApi_StringUtils.isEmpty(canDate)) {
                            if (compareDate(beginDate,endDate))
                                search();
                        }else {
                            showToast("时间不能为空",false);
                        }
                    }
                });
                break;
        }
    }

    private boolean compareDate(String begin, String end) {
        if (FreeApi_StringUtils.isEmpty(begin) | FreeApi_StringUtils.isEmpty(end)){
            return true;
        }

        int i = FreeApi_DateUtils.compare_date(end, begin, "yyyy-MM-dd");
        if (i != 1) {
            showToast("结束日期不能大于开始日期", false);
            tvBeginTime.setText("");
            tvEndTime.setText("");
            beginDate = "";
            endDate = "";
            return false;
        }

        return true;
    }


    private void  search() {
        JsonObject map = new JsonObject();
        map.addProperty("actionType", "query");
        map.addProperty("area", location);
        map.addProperty("department", classes);
        map.addProperty("djType", fromType);
        map.addProperty("startTime", beginDate + ":00");
        map.addProperty("endTime", endDate + ":59");
        map.addProperty("doTime",FreeApi_StringUtils.isEmpty(canDate) ? canDate : canDate + ":00");
        NetUtils.requestDara("HIK.PdaScSpotCheckSchedule", this, map, new FreeUI_DialogEntityCallBack<BaseResponseBean<CheckPlanBean>>
                (new TypeToken<BaseResponseBean<CheckPlanBean>>() {
                }.getType(), getSupportFragmentManager(), this) {

            @Override
            public void onSuccess(Response<BaseResponseBean<CheckPlanBean>> response) {
                super.onSuccess(response);
                if (response.body().isSuccess(getApplicationContext(), true, getSupportFragmentManager())) {
                    List<EqpCheckListBean> eqpCheckListBeans = response.body().getBody().getxPdaScSpotCheckScheduleResults();
                    List<EqpCheckListBean> checkData = new ArrayList<>();
                    checkData.clear();
                    if (eqpCheckListBeans.size() <= 0) {
                        showConfirmDialog("暂无点检计划");
                        eqpCheckListAdapter.setNewData(null);
                    } else {
                        if (!cbComplete.isChecked() & !cbCreate.isChecked()){
                            nsScroll.setVisibility(View.GONE);
                            eqpCheckListAdapter.setNewData(eqpCheckListBeans);
                        }else {
                            for (EqpCheckListBean data : eqpCheckListBeans){
                                String status = data.getStatus();
                                if (cbCreate.isChecked()){
                                    if (status.equals("CREATE") | status.equals("WARNING")
                                            | status.equals("CANSTART") | status.equals("START")){
                                        checkData.add(data);
                                    }
                                }

                                if (cbComplete.isChecked()){
                                    if (status.equals("COMPLETE")){
                                        checkData.add(data);
                                    }
                                }
                            }

                            if (checkData.size() <= 0){
                                showConfirmDialog("当前状态下无点检计划");
                                eqpCheckListAdapter.setNewData(null);
                            }else {
                                nsScroll.setVisibility(View.GONE);
                                eqpCheckListAdapter.setNewData(checkData);
                            }
                        }
                    }
                }
            }

            @Override
            public void onError(Response<BaseResponseBean<CheckPlanBean>> response) {
                super.onError(response);
                loadError(response.getException(), "HIK.PdaScSpotCheckSchedule");
            }
        });
    }

    @Override
    protected void onRestart() {
        super.onRestart();

        if (FreeApi_StringUtils.isEmpty(location)){
            return;
        }

        if ((!FreeApi_StringUtils.isEmpty(beginDate) && !FreeApi_StringUtils.isEmpty(endDate)) | !FreeApi_StringUtils.isEmpty(canDate)) {
            if (compareDate(beginDate,endDate))
                search();
        }else {
            showToast("时间不能为空",false);
        }
    }

    @Override
    public void onItemClick(BaseQuickAdapter adapter, View view, int position) {
        EqpCheckListBean item = eqpCheckListAdapter.getData().get(position);
        switch (item.getStatus()) {
            case "CREATE"://创建
            case "WARNING"://警告
            case "CANSTART"://可以开始
                FreeApi_DialogUtils.getConfirmAndCancelDialog(this, "是否开始生产点检?", () -> {
                    JsonObject map = new JsonObject();
                    map.addProperty("actionType", "startSchedule");
                    map.addProperty("scheduleRrn", item.getObjectRrn());
                    NetUtils.requestDara("HIK.PdaScSpotCheckSchedule", this, map, new FreeUI_DialogEntityCallBack<BaseResponseBean<?>>(
                            new TypeToken<BaseResponseBean<?>>() {
                            }.getType(), getSupportFragmentManager(), this) {

                        @Override
                        public void onSuccess(Response<BaseResponseBean<?>> response) {
                            super.onSuccess(response);
                            if (response.body().isSuccess(getApplicationContext(), false, getSupportFragmentManager())) {
                                item.setStatus("START");
                                adapter.notifyItemChanged(position);
                                Bundle bundle = new Bundle();
                                bundle.putString("scheduleRrn", item.getObjectRrn());
                                bundle.putString("comPersonType",item.getComPersonType());
                                FreeApi_Utils.skipWithExtraIntent("header", bundle, From_CheckPlanFromActivity.this, From_checkPlanDetailsActivity.class);

                            }
                        }

                        @Override
                        public void onError(Response<BaseResponseBean<?>> response) {
                            super.onError(response);
                            loadError(response.getException(), "HIK.PdaScSpotCheckSchedule");
                        }
                    });
                }, () -> {
                }).show(getSupportFragmentManager(), "EQPKEEP");
                break;
            case "START"://已开始
            case "FORM"://已临时保存
                Bundle bundle = new Bundle();
                bundle.putString("scheduleRrn", item.getObjectRrn());
                bundle.putString("comPersonType",item.getComPersonType());
                FreeApi_Utils.skipWithExtraIntent("header", bundle, From_CheckPlanFromActivity.this, From_checkPlanDetailsActivity.class);
                break;
            case "COMPLETE"://已完成
                showToast("当前点检项已完成", false);
                break;
            case "TIMEOUT"://超时
                showToast("当前点检项已超时", false);
                break;
            default:
                break;
        }
    }

}
